package dtaskboard.client.project.dialog;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import dtaskboard.client.Constants;
import dtaskboard.client.DialogUtil;
import dtaskboard.client.project.ProjectPage;
import dtaskboard.client.service.ProjectService;
import dtaskboard.client.service.ProjectServiceAsync;

public class CloseSprintDialog extends DialogBox {

  private final TextBox achievedHours;

  public CloseSprintDialog(String projectName) {
    this.achievedHours = new TextBox();

    Label achievedLabel = new Label("Horas entregues");

    Panel panel = new VerticalPanel();

    panel.add(achievedLabel);
    panel.add(this.achievedHours);
    panel.add(new CloseSprintButton(projectName));


    super.setAnimationEnabled(true);
    super.setAutoHideEnabled(true);
    super.setHTML("Encerramento de sprint");
    super.setGlassEnabled(true);
    super.setModal(true);
    super.setWidget(panel);
    super.setVisible(true);
  }

  class CloseSprintButton extends Button {
    public CloseSprintButton(final String projectName) {
      this.setText("Encerrar sprint");
      this.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
          ProjectServiceAsync projectService = GWT.create(ProjectService.class);
          final CloseSprintDialog csd = CloseSprintDialog.this;
          String sessionId = Cookies.getCookie(Constants.sessionIdCookie);
          projectService.closeSprint(projectName, csd.achievedHours.getText(),
              sessionId, new AsyncCallback<Void>() {

                @Override
                public void onFailure(Throwable caught) {
                  DialogUtil.closableDialog("Encerramento de sprint",
                      "Houve um erro ao encerrar o sprint.");
                }

                @Override
                public void onSuccess(Void result) {
                  DialogUtil.closableDialog("Encerramento de sprint",
                      "Sprint encerrado com sucesso.");
                  csd.hide();
                  new ProjectPage(projectName);
                }


              });

        }
      });
    }
  }

}
